/**
 * @Author: Hhx06
 * @Email: huangshm@yoozoo.com
 * @Description:
 * @File:  req
 * @Version: 1.0.0
 * @Date: 2022/06/10 16:57
 */

package message

import (
	"encoding/json"
	"github.com/eyotang/boomer"
	log "github.com/leesper/holmes"
	"github.com/pkg/errors"
	"github.com/valyala/fasthttp"
	"httpTemplate/cache"
	"httpTemplate/client"
	"httpTemplate/model"
	"httpTemplate/stats"
)

func VerifyReq(ctx boomer.Context, c *client.Client, url string) bool {
	r3 := cache.GetRedis()
	l, err := r3.LpopString("ob-hhx-all")
	r3.Close()
	if err != nil {
		stats.RecordFailure("redis", "fail-verify1", 0, err.Error())
		return false
	} else {
		stats.RecordSuccess("redis", "success-verify1", 0, 0)
	}
	ctx.Set("login", l)

	if err := errors.WithStack(c.NewRequest(ctx, client.ParseURI(url), verifyResp).GET().URL(url).Do().Error); err != nil {
		err = errors.Errorf("Request [%s] failed, err: %+v", client.ParseURI(url), err)
		return false
	}
	return true

}

func verifyResp(ctx boomer.Context, statusCode int, body []byte) (err error) {
	if statusCode != fasthttp.StatusOK {
		err = errors.Errorf("%s %s", statusCode, fasthttp.StatusMessage(statusCode))
		log.Errorf("HTTP Status Code: %s %s", statusCode, fasthttp.StatusMessage(statusCode))
		return
	}
	if len(body) == 0 {
		err = errors.Errorf("not response data")
		log.Errorf("not response data")
		return
	}

	var resp model.Resp
	if err = json.Unmarshal(body, &resp); err != nil {
		err = errors.Errorf(" json parse err, data is %s,err is %v", string(body), err)
		log.Errorf(" json parse err, data is %s,err is %v", string(body), err)
		return
	}

	if resp.Code == "1" {
		r4 := cache.GetRedis()
		l, _ := ctx.GetString("l")
		err = r4.RpushString("ob-hhx-all", l)
		r4.Close()
		if err != nil {
			stats.RecordFailure("redis", "fail-recv-verify2", 0, err.Error())
		} else {
			stats.RecordSuccess("redis", "success-recv-verify2", 0, 0)
		}
		return
	}
	err = errors.Errorf("resp data err, status is %s, desc is %s", resp.Code, resp.Msg)
	log.Errorf("resp data err, status is %s, desc is %s", resp.Code, resp.Msg)
	return
}
